package com.xinchen.aiowaste.ui.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.maple.model.data.MainMenuData
import com.maple.utils.ext.layoutInflater
import com.maple.utils.util.UIUtils
import com.xinchen.aiowaste.R

class MainMenuAdapter(val context: Context): RecyclerView.Adapter<MainMenuAdapter.ViewHolder>(){

    private val list: MutableList<MainMenuData> = mutableListOf()

    private var listener: OnClickListener? = null

    fun setListener(l: OnClickListener?) {
        listener = l
    }

    fun setData(l: List<MainMenuData>?) {
        if(!l.isNullOrEmpty()) {
            this.list.clear()
            this.list.addAll(l)
            this.notifyDataSetChanged()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainMenuAdapter.ViewHolder {
        val view: View = context.layoutInflater.inflate(R.layout.item_main_menu, parent, false)
        val holder: ViewHolder = ViewHolder(view)
        holder.itemRoot.setOnClickListener {
            listener?.onItemClick(
                holder.bindingAdapterPosition,
                list.get(holder.bindingAdapterPosition),
            )
        }
        return holder
    }

    override fun onBindViewHolder(holder: MainMenuAdapter.ViewHolder, position: Int) {
        holder.setData(position,list.get(position))
    }

    override fun getItemCount(): Int = list.size

    inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
        val itemRoot: LinearLayout = itemView.findViewById(R.id.item_root)
        private val tvName: TextView = itemView.findViewById(R.id.tv_name)
        private val tvEName: TextView = itemView.findViewById(R.id.tv_ename)
        private val ivIcon: ImageView = itemView.findViewById(R.id.iv_icon)
        fun setData(position: Int,data: MainMenuData) {
            with(data) {
                tvName.text = name
                tvEName.text = eName
                ivIcon.background = UIUtils.getDrawable(icon)
            }
        }

    }

    interface OnClickListener {
        fun onItemClick(pos: Int = 0, item: MainMenuData?)
    }
}